import { observable, action, toJS } from 'mobx';
import * as API_LIST from '../apis/dialog';
import {message} from 'antd';
import { WeaForm, WeaTableNew, WeaLogView} from 'comsMobx';
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import isEmpty from 'lodash/isEmpty';
import isArray from 'lodash/isArray';
import mapKeys from 'lodash/mapKeys';
import mapValues from 'lodash/mapValues';
const { TableStore } = WeaTableNew;
const getKey = WeaTools.getKey;
const types = WeaTools.types;
const getLabel = WeaLocaleProvider.getLabel;
const {LogStore} = WeaLogView;

function getValueByfield(field) {
	const type = typeof (field.conditionType) == 'string' ? field.conditionType.toUpperCase() : field.conditionType;
	if (typeof (type) == 'string') {
		let arrs = [types.INPUT, types.CHECKBOX, types.DATEPICKER, types.TIMEPICKER, types.TEXTAREA, types.SWITCH, types.INPUTNUMBER];
		if (arrs.indexOf(type) > -1) {
			if (field.value !== undefined) {
				return {
					value: field.value
				}
			}
		}
		if (types.SELECT === type) {
			let value = WeaTools.getSelectDefaultValue(field.options);
			if (field.value !== undefined) value = field.value;
			if (value !== undefined) {
				return {
					value: value
				}
			}
		}
		if (types.BROWSER === type) {
			if (!isEmpty(field.browserConditionParam)) {
				const replacesDatas = field.browserConditionParam.replaceDatas || field.browserConditionParam.valueObj;
				if (!isEmpty(replacesDatas)) {
					let values = [], names = [];
					replacesDatas.forEach((d) => {
						values.push(d.id);
						names.push(d.lastname || d.name); // 人力按钮特殊处理
					})
					return {
						value: values.join(','),
						valueSpan: names.join(','),
						valueObj: replacesDatas
					}
				}
			}
		}
		if (types.DATE === type) {
			let selectValue = '0', startValue = null, endValue = null;
			if (!isEmpty(field.options)) selectValue = WeaTools.getSelectDefaultValue(field.options) || selectValue;
			if (!isEmpty(field.value)) {
				selectValue = field.value[field.domkey[0]];
				startValue = field.value[field.domkey[1]];
				endValue = field.value[field.domkey[2]];
			}
			return {
				value: [selectValue, startValue, endValue]
			}
		}
		if (types.SELECT_LINKAGE === type) {
			let selectValue = WeaTools.getSelectDefaultValue(field.options) || '0';
			return {
				value: [selectValue]
			}
		}
		if (types.SCOPE === type) {
			let sValue = field.startValue || '', eValue = field.endValue || '';
			return {
				value: [sValue, eValue]
			}
		}
		if (types.RANGEPICKER === type) {
			let sValue = field.startDate || field[field.domkey[0]] || '', eValue = field.endDate || field[field.domkey[1]] || '';
			return {
				value: [sValue, eValue]
			}
		}
    if (types.UPLOAD === type) {
      if (field.datas && !isEmpty(field.datas)) {
        const value = field.datas.map(t => t.fileid || t.id).join(',');
        return {
          value,
          valueSpan: field.datas,
        };
      }
    }
	} else {
		let value = []
		type.forEach((record, index) => {
			value.push({
				value: field.value[index]
			});
		})
		return value;
	}
}

class MyForm extends WeaForm {
	constructor(props) {
		super(props);
	}

	@action
	initFormFields = (condition, callback) => {
		let fields = {};
		let values = {};
		condition && condition.map(c => {
      c.items && c.items.map(f => {
				this.fieldArr.push(f);
				const field = {};
				let key = getKey(f);
				let v = getValueByfield(f) || {value: f.value || ''};
				let oldKey = key.split('__');
				if (oldKey.length > 1) {
					oldKey.forEach((e, index) => {
						fields[e] = {
							label: e
						};
					})
					if (v) {
						oldKey.forEach((record, index) => {
							values[oldKey[index]] = v[index];
						})
					}
				} else {
					if (v) values[key] = v;
					// 初始化fields
					field.label = f.label;
					if (f.rules) field.rules = f.rules;
					fields[key] = field;
				}

			});
		})
		this.initFields({ fields });
		this.updateFields(values); //根据默认条件初始化值
		this.isFormInit = true;
	}

	updateFields = (datas, updateAll = false) => {
		if (updateAll) this.resetConditionValue();
		const fields = this.fields;
		_.each(datas, (data, k) => {
      let item = fields.get(k);
			if (!item) { // 没work，之后再解决
				this.add(k);
			}else{
        if (isArray(data) && data.length > 0) {
          data.forEach((record) => {
            if (_.isString(record)) {
              item.value = record;
            } else {
              item.value = record.value;
              item.valueSpan = record.valueSpan;
              item.valueObj = record.valueObj;
            }
          })
        } else {
          if (_.isString(data)) {
            item.value = data;
          } else {
            item.value = data.value;
            item.valueSpan = data.valueSpan;
            item.valueObj = data.valueObj;
          }
        }
      }
		})
	}

	getError = (field) => {
		let msg = '';
		const key = getKey(field);
		const target = this.$(key);
		if (target) msg = target.errors();
		return msg;
	}
}

export default class Dialog {
	@observable meetingTopicDefaultValue = 0;
	@observable meetingServiceDefaultValue = 0;
	@observable topicViewActive = false;
	@observable serviceViewActive = false;
	@observable overMeetingDialogVisiable = false;
	@observable overMeetingDialogVisiable = false;
	@observable governVisiable = false;
	@observable governDecisionVisiable = false;
	@observable nowValue=new Date();
	@observable cataconditions = null;
	@observable cataDecisionconditions = null;
	@observable userList = [];
	@observable form = {
		'create': new MyForm()
	}
	@observable logStore = new LogStore();
	@observable canRender = false;
	@observable comsWeaTableStore = {};
	@observable comsSignDetailWeaTableStore = {};
  @observable MeetingMemberExportExcelUrl = '';
  @observable oldSecretLevel = '3';
  @observable baseDocFlowColumn = [];//会议信息中的文档流程字段,密级需要加参数
  @observable serviceDocFlowColumn = [];
  @observable topicDocFlowColumn = [];
  @observable topicResultDatas = [];
  @observable topicTidyDatas = [];
  @observable copyIndex = [0];//因为议程整理中是根据topic_data来判断是新增还是更新,所以在列表复制的情况下topic_data也会复制出来影响插入操作,用这个字段来记录复制索引来删除复制出来的topic_data
  @observable accessoryBaseInfo = {};
	@observable weaDialogContentHeight = 454; // 弹框内容滚动高度
	@observable memberReceiptStore={
		backdate: '',
		backtime: '',
		begindate: '',
		begintime: '',
		bookroom: '',
		bookticket: '',
		isattend: '',
		memberid: '',
		recRemark: '',
		recorderid: '',
		roomstander: '',
		ticketstander: '',
		othermember: '',
	};
	@observable zIndex = 801;
	@observable cusPreivewTab={};
	@observable categoryCheckArr=[];
	@observable categoryDefault='';
	@observable categoryDecisionDefault='';
	@observable cateStr = '';
	@observable cateDecisionStr = '';
	
	@observable hrmTabel = new TableStore({dataHandle: (datas) => {
    datas.forEach((data) => {
      if (typeof(data.otherMemberListspan) == 'string') {
        data.otherMemberListspan = data.otherMemberListspan ? JSON.parse(data.otherMemberListspan) : undefined;
      }
    });
    return datas;
  }});
	
	@observable crmTabel = new TableStore({dataHandle: (datas) => {
    datas.forEach((data) => {
      if (typeof(data.otherMemberListspan) == 'string') {
        data.otherMemberListspan = data.otherMemberListspan ? JSON.parse(data.otherMemberListspan) : undefined;
      }
    });
    return datas;
  }});

	@observable dialogStatus = {
		dialogTitle: `${getLabel(15008,'新建会议')}`,
		loading: false,
		saveLoading: false,
		submitLoading: false,
		repeatLoading: false,
		type: 'create',
		visible: false,//visible为弹出框显示状态
		meetingId: '',//会议id
		previewmeetingTab: 1,
		previewButtons: [],//查看会议按钮
		tabs: '',
		tabbase: '',
		tabTopic: '',
		tabService: '',
		tabmember: '',
		tabSign: '',
		tabDecision: '',
		tabdiscuss: '',
		tabSignTable: '',
		tabSignDetailTable: '',
		tabDecisionTable: '',
		tabSignTab: false,
		exchangeList: '',
		// decisionStatus: '',
    editDatas: '',
    hasCaller:false,
	meetingname:'',
	meetingBeginDate:'',
	meetingEndDate:'',

		conditions: {},//需要区分开通过会议ID
		topicColumns: [],
		topicDatas: [],
		serviceColumns: [],
		serviceDatas: [],
    copyServiceDatas: [], //存放上一次 会议服务的datas
		serviceKeycol: '',

		advanceModal: false,
		advanceModalparams: '',
		allCreateDatas: {},//新建值存值的地方（议程和服务和特殊的基本信息）还有投屏的设置

		RoomPlanContainer: false,
		isNewForm: true,
		jurisdiction: {},
		canSet: {},
    chatVisible:false,
    msginfo:[],
    isPro:false,//用于判断是否为OA正式系统,打开客户linkUrl需要改变
		endRepeatLoading: false, //提前结束重复会议提交处理
		maxRepeatDate:'', //周期会议最大跨度
		logSmallType:'',
		logType:'',
    targetId:'',
    onlyFlowCreate:0,//是否只允许使用流程新建会议
    hideCreateEntry:0,//是否隐藏新建入口,只能通过流程模块新建会议
    workflowBaseIds:'',//新建会议流程使用的workflow_base对应的id
    addRequestUrlParams : '',
		requestFieldIds:{},//在从会议室使用情况新建的时候对应只有一条流程打开时候需要带出参数
		createInit:false,

	};
  @observable customField = []
	//会议决议页面数据
	@observable decisionStatus = {};
	@observable decisionToGovernBtn = false;
  // @observable decisionStatus = {
  //   decisionTableDatas: [], //会议决议table的数据
  //   decision: '',
  //   decisiondoc: [],//文档
  //   decisioncrmids: [],//客户
  //   decisionprjids: [],//项目
  //   decisiontskids: [],//任务
  //   decisionwfids: [],//流程
  //   decisionatchids: [],//附件
  // }
	@observable uploadParams = {}; //上传附件默认参数
	@observable uploadKeys = [];
	@observable topic_uploadKeysArr = []; // 存储议程上传附件的keys

	@observable loaded = false;

	//打屏签到数据 fix:新建-->查看，获取大屏签到数据不对问题
	@observable screenParams = {
    fontsize: '16',
    bgcolor: '#006699',
    fontcolor: '#ffffff',
    showhead: '1',
    showdep: '1',
    showsub: '1',
    shownum: '1',
    showtitle: '1',
		bgimg: '',
		bgimgLoadlink: '',
	cfg: {},
	allowSignBack:'1',
	    afterSignCanBack:'5',
	    defaultAllowSignTime:'5',
	    defaultAllowSignBackTime:'30',
  }
  
  //接口耗时开始时间
  @observable interfaceTc_start = ''

  //接口耗时结束时间
  @observable interfaceTc_after = ''

  //服务端耗时
  @observable server_duration = ''

  //渲染耗时开始时间
  @observable renderTc_start = ''

  //渲染耗时结束时间
  @observable renderTc_after = ''

  //总耗时开始时间
  @observable allTc_start = ''

  //总耗时结束时间
  @observable allTc_after = ''

	@observable other_member = {};

	
	// 会议签到,签退 start
	@observable signStatus = {
		form: new WeaForm(),
		conditionInfo: [],
		weaTableStore: {},
		signSessionkey: '',
		limitForm: new WeaForm(),
		limitConditionInfo: [],
		limitDialogVisible: false,
		signType: ''
	}

	@observable signDataStatistic = {
		allMember: 0, //应签到
		signCount: 0, //已签到
		notSignCount: 0, // 未签到
		signBackCount: 0, // 已签退
		notSignBackCount: 0, // 未签退
		ztrs: 0, // 早退 
		cdrs: 0, // 迟到
		allowSignBack:false
	}
	// 会议签到,签退 end

	// 为了满足无侵入开发部分-start
	@observable ecCallerVisible = true;  //  召集人显示
	@observable previewMeetingResultInfo = {}; 
	// 为了满足无侵入开发部分-end

	@observable meetingTabVisible = [];
	@observable meetingCreateTabs = [];
	@observable meeetingDateVisible = true; 
	@observable dialogType = "";
	@observable isLimitCreateMeetingBeginEndTime = false; // 是否开启新建会议时开始时间结束的限制
	@observable arrangeTopicParams = {
		arrangeTopic: 1
	};
	@observable setEditTableCloumnCount = 8;
	@observable topicTidyDialogHeight = 400;

	@action

	setState = (params={}) => {
		Object.keys(params).forEach(key => {
			this[key] = params[key];
		});
	}

	setMeetingTabVisible = (tabs={}) => {
		if (tabs) {
			let obj = [];
			for(let i in tabs) {
				if(tabs[i]) {
					obj.push(i);
				}
			}
			this.meetingTabVisible = obj;
		}
	}

	getMeetingTabElement = () => { 
		// 新建会议-会议签到走的单独接口判断
		API_LIST.getMeetingTabElement().then((result) => {
			if (result && result.api_status) {
				this.meetingCreateTabs = result.meetingTabElementValue || [];
				const type = this.dialogStatus.type
				type == 'create' && setTimeout(()=>this.getCreateBaseInfo(result.meetingTabElementValue),0)
			}
    })
	}

	@action addPreivewTabs=(key,title,url)=>{
		let cusUrl={};
		cusUrl['cus_'+key]={"title":title,"url":url};
		this.cusPreivewTab={...this.cusPreivewTab,...cusUrl}
	}

	setLoaded = (bool) => this.loaded = bool;
	setOldSecretLevel = (val) => this.oldSecretLevel = val;
	setUploadParams = (params) => {
    const uploadParams = toJS(this.uploadParams);
		Object.keys(params).forEach(key => {
      uploadParams[key] = {
				...uploadParams[key],
				...params[key]
			}
		})
		this.uploadParams = uploadParams;
	}

  setUploadCommonParams = (params) => {
    const uploadParams = toJS(this.uploadParams);
    const uploadKeys = toJS(this.uploadKeys);
    uploadKeys.length > 0 && uploadKeys.map(key => {
    	uploadParams[key] = {
				...uploadParams[key],
				...params
			}
		})
    this.uploadParams = uploadParams;
	}
	
	setAccessoryBaseInfo = (params) => {
    const accessoryBaseInfoTemp = {...this.accessoryBaseInfo,...params};    
    this.accessoryBaseInfo = accessoryBaseInfoTemp;
  }

  addCustomField = (params = [])=>{
    this.customField = params
  }

  setDialogState = (params = {}) => {
		let dialogStatus = {...this.dialogStatus};
    Object.keys(params).forEach(key => {
      dialogStatus[key] = params[key];
    });
    this.dialogStatus = dialogStatus;
  }

  setDecisionStatus = (params) => {
    let decisionStatus = {...this.decisionStatus};
    Object.keys(params).forEach(key => {
      decisionStatus[key] = params[key];
    });
    this.decisionStatus = decisionStatus;
	}

	//大屏签到数据处理
  setScreenParams = (params) => {
  	this.screenParams = {
			...this.screenParams,
			...params,
		}
	}

	initScreenParams = () => {
    this.screenParams = {
      fontsize: '16',
      bgcolor: '#006699',
      fontcolor: '#ffffff',
      showhead: '1',
      showdep: '1',
      showsub: '1',
      shownum: '1',
      showtitle: '1',
			bgimg: '',
			bgimgLoadlink: '',
      cfg: {},
    }
	}

	//打开会议室使用情况，带入开始日期
	addDate = (meetingid) => {
    let formKey = meetingid || 'create';
    let val = this.getFormParams(formKey)
		return val.begindate;
	}
	
	addUser(params) {
		this.userList.push({ name: "dyf" });
	}
	
	deleteForm = (meetingId) => {
		delete this.dialogStatus.conditions[meetingId]
	}
	
  deleteForms = (meetingId) => {
		this.form = {};
  }
	doNewForm = (key, callback, type) => {
		let has = false
		for (let index in this.form) {
			if (index == key) has = true
		}
		if (has && key == 'edit') {
			this.form = { ...this.form, [`${key}_edit`]: new MyForm() }
			if (callback) callback(this.form[`${key}_edit`])
		} else {
			this.form = { ...this.form, [key]: new MyForm() }
			if (callback) callback(this.form[key])
		}
	}
	
	changeNewForm = (value) => {
		this.dialogStatus = {
			...this.dialogStatus,
			isNewForm: value,
		}
	}
	
	getFormParams = (key) => {
		key = key ? key : 'create';
		if (!this.form[key]) {
			return false
		}
		return this.form[key].getFormParams();
  }
  
  getFormBrowserType = (domkey,key) => {
		key = key ? key : 'create';
    let conditions = this.dialogStatus.conditions[key];
    let browserType = '';
    conditions.length!==0 && conditions.map(c => {
      c && c.items && c.items.map(fields => {
        if(fields.domkey[0] == domkey){
          browserType = fields.conditionType
        }
      })
    })
		return browserType;
	}

	getUserList(params) {
		return this.userList.slice();
	}

  doInit = (type, visible, meetingId, callback) => {//type为弹出框类型，visible为弹出框显示状态
		if (callback) callback();
	}

	setRoomPlan = (bool) => {
		this.dialogStatus = {
			...this.dialogStatus,
			RoomPlanContainer: bool,
		}
	}
	
  //加这个的作用是为了使所有调用会议模块的时候不管是打开新建流程页面还是弹出框,不管是直接window.open还是dialog都可以控制
  getRequestParams = ()=>{
    API_LIST.getRequestParams().then((result) => {
      this.setRequestParams(result)
    })
  }

  setRequestParams = (result)=>{
    this.dialogStatus = {
      ...this.dialogStatus,
      onlyFlowCreate:result.onlyFlowCreate&&result.onlyFlowCreate || 0,
      hideCreateEntry:result.hideCreateEntry&&result.hideCreateEntry || 0,
      workflowBaseIds:result.workflowBaseIds&&result.workflowBaseIds || '',
      requestFieldIds:result.requestFieldIds&&result.requestFieldIds || {},
    }
      //如果开启了只能使用流程那么就将对应参数加上
      if(result.onlyFlowCreate==1 && result.hideCreateEntry==0){
        let urlParamsTemp = [];
        result.requestFieldIds&&Object.keys(result.requestFieldIds).map((item)=>{
          if(item == 'begindate'){
            result.requestFieldIds.begindate&&result.requestFieldIds.begindate.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.beginDate}`)
            })
          }
          if(item == 'begintime'){
            result.requestFieldIds.begintime&&result.requestFieldIds.begintime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.beginTime}`)
            })
          }
          if(item == 'enddate'){
            result.requestFieldIds.enddate&&result.requestFieldIds.enddate.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.endDate}`)
            })
          }
          if(item == 'endtime'){
            result.requestFieldIds.endtime&&result.requestFieldIds.endtime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.endTime}`)
            })
          }
          if(item == 'address'){
            result.requestFieldIds.address&&result.requestFieldIds.address.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.address}`)
            })
          }
          if(item == 'beginDateTime'){
            result.requestFieldIds.beginDateTime&&result.requestFieldIds.beginDateTime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.beginDate} ${result.beginTime}`)
            })
          }
          if(item == 'endDateTime'){
            result.requestFieldIds.endDateTime&&result.requestFieldIds.endDateTime.map(item1=>{
              urlParamsTemp.push(`&${item1}=${result.endDate} ${result.endTime}`)
            })
          }
        })
        this.dialogStatus = {
          ...this.dialogStatus,
          addRequestUrlParams: urlParamsTemp.join('')
        }
    }
  }

  getCategoryConditions =(params) =>{
    return API_LIST.getCategoryConditions(params)
  }

  getCategoryDecisionConditions =(params) =>{
    return API_LIST.getCategoryConditions(params)
  }

	
	getPreview = (params, callback, callback2) => {
		this.dialogStatus.type = 'preview'; // 为无侵入开发获取当前操作类型-2019-10-17
		this.dialogType = 'preview';
		this.dialogStatus.meetingId = params.meetingid; // 为无侵入开发获取当前操作类型-2019-10-17
		this.getApi_duration_start();
		this.canRender = false;
		API_LIST.getPreview(params).then((result) => {
			if (result.error != 'noright' && result.error != 'noSecretRight' && result.error != 'noData') {
        this.getApi_duration_after()
        this.accessoryBaseInfo = result.base.accessoryBaseInfo;
        result.base.apiCost&&this.setServer_duration(result.base.apiCost)
        this.oldSecretLevel=result.base.secretLevel;
				let exchange = { ...result.exchange }
				exchange.datas.forEach((element, index) => {
					element.isEdit = false
				})
				exchange.datas.unshift({
					id: 'create',
					isEdit: true,
					remark: '',
					docids: [],
					projectids: [],
					relatedcus: [],
					relateddoc: [],
					relatedprj: [],
					relatedwf: [],
				});
				let conditions = { ...this.dialogStatus.conditions, [params.meetingid]: result.base.datas }
				this.doNewForm(params.meetingid,(form) => {
					form.conditions = [];
					form.resetForm();
					form.initFormFields(result.base.datas)
					this.changeNewForm(true)
				})
				
				let canSet = { ...this.dialogStatus.canSet, [params.meetingid]: result.base.canset }
				if(result.sign.qrcode) result.sign.qrcode = decodeURIComponent(result.sign.qrcode)//url解码
				this.dialogStatus = {
					...this.dialogStatus,
					previewButtons: result.base.btns,
					tabs: result.tabs,
					tabbase: result.base,
					tabTopic: result.base.topic,
					tabService: result.base.service,
					tabMember: result.member,
					tabSign: result.sign,
					tabDecision: result.decision,
					tabDiscuss: result.discuss,
					exchangeList: exchange,
					conditions: conditions,
					meetingBeginDate:result.base.beginDate+" "+result.base.beginTime,
					meetingEndDate:result.base.endDate+" "+result.base.endTime,
					jurisdiction: {
						...this.dialogStatus.jurisdiction,
						[params.meetingid]: ''
					},
					canSet: canSet,
					maxRepeatDate: result.base.maxRepeatDate,
					logSmallType: result.logSmallType,
					logType: result.logType,
          targetId: params.meetingid,
          msginfo: result.base.msgInfo&&result.base.msgInfo,
          isPro: result.base.isPro,
          meetingname:result.base.meetingname,
          serviceKeycol: result.base.service.keycol,
				}

				this.decisionToGovernBtn = result.base.decisionToGovernBtn;
				const hrmSessionkey = result.member.hrmdatas.sessionkey;
				this.hrmTabel.getDatas(hrmSessionkey,1, '', '');
				const crmSessionkey = result.member.crmdatas.sessionkey;
        this.crmTabel.getDatas(crmSessionkey,1, '', '');
        const memberInfo = result.member.hrmdatas.memberCount.data
        let tabMember = {...this.dialogStatus.tabMember,hrmnum:memberInfo.attend+memberInfo.otherCount,crmnum:memberInfo.crmAttend,
          allAttend:memberInfo.allAttend,allCrmAttend:memberInfo.allCrmAttend}
        this.setDialogState({tabMember:tabMember})
        if(result.base.service && result.base.service.datas){
          this.initAllCreateDatas("service",result.base.service.datas);
        }
				if (callback) callback(result.base.datas)
				if(callback2)callback2(result.decision)
				//加载自定义页签
				window.eventRegister.startList("addMeetingPrivewCusTab",function(){},function(){});
			}
			this.dialogStatus.repeatLoading=false;
			this.dialogStatus.submitLoading=false;
      this.dialogStatus.saveLoading=false;
      //渲染结束
      this.setRender_after()
      //总耗时结束
      this.setAll_after()
      //调用系统耗时接口
			this.saveSystemPageViewLog({moduleType:'10'})
			
			this.setMeetingTabVisible(result.tabs);//tabs

			if (result.error == 'noright' || result.error == 'noSecretRight' || result.error == 'noData') {

				this.dialogStatus = {
					...this.dialogStatus,
					jurisdiction: {
						...this.dialogStatus.jurisdiction,
						[params.meetingid]: result.error
					},
					previewButtons: []
				}
				if (callback) callback(false)
			}
			this.canRender = true;
			this.previewMeetingResultInfo = { ...result };
		}
		)
		//this.getCategoryConditions({'type':'8'})
		//this.getCategoryDecisionConditions()
	}

	getCreate = (type, params, callback) => {
		this.canRender = false;
		this.dialogStatus.type = type; // 为无侵入开发获取当前操作类型-2019-10-17
		this.dialogType = type;
    type == 'create'?(this.dialogStatus.meetingId = ''):(this.dialogStatus.meetingId = params.meetingid);
    //下面两句话业务逻辑:如果传值为空就会影响无侵入开发自定义字段
    type == 'create' && params.begintime =='' && delete params.begintime;
		type == 'create' && params.endtime =='' && delete params.endtime;
		if(params && (params.address === undefined || params.address === '')) {
			delete params.address;
		}
		if(!this.meeetingDateVisible && params) {
			delete params.meetingDate;
			delete params.begintime;
			delete params.endtime;
		}
		API_LIST.getMeetingBaseField(params).then((result) => {
			this.meetingTopicDefaultValue = result.meetingTopicDefaultValue;
			this.meetingServiceDefaultValue = result.meetingServiceDefaultValue;
			this.setMeetingTabVisible(result.tabs);// tabs
			this.setState({ meeetingDateVisible: true }); // 请求完接口后将meeetingDateVisible=true，避免影响下次新建
      this.oldSecretLevel = result.secretLevel;
      this.baseDocFlowColumn = result.baseDocFlowColumn;
      this.accessoryBaseInfo = result.accessoryBaseInfo;
			result.datas && result.datas.length > 0 && result.datas.map(v => {//处理会议室和自定义会议室（都设置为可编辑）
				v.items && v.items.length > 0 && v.items.map(item => {
          if(item.domkey[0] == 'address' || item.domkey[0] == 'customizeAddress'){
            item.viewAttr = 2;
            if(item.rules){item.rules = '';}
          }
          if(item.domkey[0] == 'hrmmembers' || item.domkey[0] == 'hrmDepartments' || item.domkey[0] == 'hrmSubCompanys'){
            // item.viewAttr = 2;
            // if(item.rules){item.rules = '';}
          }

          if(item.conditionType == 'UPLOAD'){
						this.uploadParams = {
							...this.uploadParams,
              [item.domkey[0]]: {
                autoUpload: item.autoUpload || true,
                listType: item.listType || 'list',
                limitType: item.limitType || '',
                uploadUrl: item.uploadUrl || '',
                maxUploadSize: item.maxUploadSize || 0,
                mixUploadSize: item.mixUploadSize || 0,
                viewAttr: item.viewAttr || 2,
                showClearAll: item.showClearAll || false,
                category: item.category || '',
                errorMsg: item.errorMsg || '',
                datas: item.datas || [],
              }
						}
						this.uploadKeys = [...this.uploadKeys, item.domkey[0]]
					}
				})
			})
      if (type == 'create') {
				this.dialogStatus = {
					...this.dialogStatus,
					conditions: {
						...this.dialogStatus.conditions,
						'create': result.datas,
					},
					canSet: {
						...this.dialogStatus.canSet,
						'create': result.canSet,
					},
					maxRepeatDate:result.maxRepeatDate,
					createInit:true,
					hasCaller:result.hasCaller,
				}
        this.setRequestParams(result)
        
				if (callback) callback(result.datas)
				
				this.initAllCreateDatas("service",[]);
				this.initAllCreateDatas("topic",[]);
			} else {//编辑
				this.doNewForm(params.meetingid,(form) => {
					form.conditions = [];
					form.initFormFields(result.datas)
					this.changeNewForm(true)
				})
				let conditions = { ...this.dialogStatus.conditions, [params.meetingid]: result.datas }
				this.dialogStatus = {
					...this.dialogStatus,
					conditions: conditions,
					editDatas: result,
					serviceKeycol: result.service.keycol,
          maxRepeatDate:result.maxRepeatDate,
          hasCaller:result.hasCaller,
        }
        this.topicDocFlowColumn = result.topic.topicDocFlowColumn;
        this.serviceDocFlowColumn = result.service.serviceDocFlowColumn;
        if(result&&result.service&&result.service.datas){
          this.initAllCreateDatas("service",result.service.datas);
        }
		if(result&&result.topic&&result.topic.datas){
            this.initAllCreateDatas("topic",result.topic.datas);
		}

			}
			if (callback) callback(result.datas)
			this.canRender = true;
		})
	}

	getCreateBaseInfo = (params)=>{
		if (params && params.some(v => v === 'sign')) {
			API_LIST.getScreenSet({ meetingid: '' }).then((result) => {
				this.screenParams = result;
			})
		}

		if (params && params.some(v => v === 'topic')) {
			this.getMeetingTopicField();
		}
		if (params && params.some(v => v === 'service')) {
			this.getMeetingServiceField();
		}
	}

	//初始化议程、服务，防止编辑不修改直接保存时，丢失数据
	initAllCreateDatas=(type, datas)=>{
    let {allCreateDatas} = toJS(this.dialogStatus);
    let rows = datas.length;
    let each = {};
		let alldatas = {};
    datas.forEach((element, index) => {
      each = mapKeys(element, (value, key) => {
        return key + '_' + (index + 1)
      })
      each = mapValues(each, (value, key) => {
        if(value instanceof Object && value.datas&&value.datas.length>0){
          let fieldids = value.datas.map((v)=>{
            return v.fileid
          })
          return fieldids.join(',')
        }else{
          return value
        }
      })
      alldatas = {...alldatas, ...each}
    })
    if(type == 'topic'){
      alldatas = {
          ...alldatas,
          topicrows: rows || 0,
      }
    }
    if(type == 'service'){
      alldatas = {
          ...alldatas,
          servicerows: rows || 0,
      }
		}
    this.dialogStatus={
        ...this.dialogStatus,
        allCreateDatas: {...allCreateDatas,...alldatas}
    }
	}

	//新建会议-议程
	getMeetingTopicField = value => {
		(!value || !!value.meetingid) &&
			API_LIST.getMeetingTopicField(value).then(data => {
        if(data && data.columns && data.columns.length > 0){
          this.topicDocFlowColumn = data.topicDocFlowColumn
          let count = 100 / data.columns.length;
          data.columns = data.columns.map((x) => {
            x['width'] = `${count}%`
            if (x.com[0].type == "BROWSER") {
              x.com[0].browserConditionParam.layout = document.body
            }
            return x;
          });
          this.dialogStatus = {
            ...this.dialogStatus,
            topicColumns: data.columns || [],
            topicDatas: data.datas || []
          }
        }else{
            this.dialogStatus = {
                ...this.dialogStatus,
                topicColumns: [],
                topicDatas: []
            }
        }
			});
		if (typeof (value) === 'object') {
			this.dialogStatus = {
				...this.dialogStatus,
				topicDatas: value
			}
		}
	}

	//新建会议-服务
	getMeetingServiceField = value => {
		(!value || !!value.meetingid) &&
		API_LIST.getMeetingServiceField(value).then(data => {
			if(data && data.columns && data.columns.length > 0){
        this.serviceDocFlowColumn = data.serviceDocFlowColumn
				let count = 100 / data.columns.length;
				data.columns = data.columns.map((x) => {
					x['width'] = `${count}%`
					return x;
				});
				this.dialogStatus = {
					...this.dialogStatus,
					serviceColumns: data.columns || [],
					serviceDatas: data.datas || [],
          copyServiceDatas: data.datas || [],
					serviceKeycol: data.keycol || -1,
				}
			}else{
				this.dialogStatus = {
					...this.dialogStatus,
					serviceColumns:  [],
					serviceDatas:  [],
          copyServiceDatas: [],
					serviceKeycol: -1,
				}
			}
		});

		if(typeof (value) === 'object') {
			value = value.map(item => {return{...item}});
			let dialogStatus = {...this.dialogStatus};
      dialogStatus = {
				...dialogStatus,
				serviceDatas: value,
			}
			this.dialogStatus = dialogStatus;
    }
	}

	//处理会议服务--选择服务项目带出参会人
  getNewServiceDatas = (datas) => {
		const copyServiceDatas = toJS(this.dialogStatus.copyServiceDatas);
    let promiseArray = [];
    if(datas && datas.length > 0){
			// 判断是否是拖拽导致的onchange
			let isNotDraggable = true;
			let idx = 0;
			for(let v of datas){// 根据服务项目和负责人来判断两条数据是否相同，相同+1，然后break，继续下一次遍历
				for(let _v of copyServiceDatas){
					if(v.items_46 == _v.items_46 && v.hrmids_47 == _v.hrmids_47){
						idx++;
						break;
					}
				}
			}
			if(idx === datas.length && datas.length === copyServiceDatas.length){
				isNotDraggable = false;
			}
      isNotDraggable&&datas.map((v,index) => {
        if(!v.items_46 && copyServiceDatas[index] && copyServiceDatas[index].items_46 !== ''){//删掉最后一条服务,清空服务人员
          v.hrmids_47 = '';
          v.hrmids_47span = '';
        }
        if(v.items_46 && copyServiceDatas[index]  && copyServiceDatas[index].items_46 !== v.items_46){
          promiseArray.push(API_LIST.getServeProHrmIds({items: v.items_46,hrmmembers:v.hrmids_47}).then(result => {
          	if(copyServiceDatas[index].items_46 == '' && v.items_46 !== ''){//前一次没有服务，新增服务，只有返回值不为空的时候改变
              if(result.hrmids && result.hrmids !== ''){
                v.hrmids_47 = result.hrmids;
                v.hrmids_47span = result.hrmNames;
              }
			}else {
                if(result.hrmids && result.hrmids !== ''){
                    v.hrmids_47 = result.hrmids;
                    v.hrmids_47span = result.hrmNames;
                }

			}
          }));
        }
      })
    }
    this.dialogStatus.copyServiceDatas = datas;
    return Promise.all(promiseArray).then(()=>{return datas});
	}


	//表单内容存储到store
	saveFields = (value = {}) => {
		this.dialogStatus = {
			...this.dialogStatus,
			allCreateDatas: value
		} 
  }
  
  setTopicTidyResultDatas = (value={})=>{
    this.topicResultDatas = {...value}
    
  }

  setTopicTidyDatas = (value={})=>{
		this.topicTidyDatas = {...value}
  }

  setCopyIndex = (value)=>{
    this.copyIndex = value
  }

  saveTopicTidyDatas = (params={},callback)=>{
    params = {...this.topicResultDatas,...params}
    API_LIST.saveTopicTidy(params).then(data => {
      if(data.api_status){
        this.getTopicData4Meeting({meetingid:params.meetingid});
        if(typeof callback == 'function'){
          callback();
        }
      }
    })
  }

  //从整理议程中回写数据到会议议程
	getTopicData4Meeting = (params) => {
		let tabTopicTemp = this.dialogStatus.tabTopic
		this.dialogStatus = {
			...this.dialogStatus,
			tabTopic:{...tabTopicTemp,datas:[]}
		}
    API_LIST.getMeetingTopicField(params).then((result) => {
      this.dialogStatus = {
        ...this.dialogStatus,
        tabTopic:{...tabTopicTemp,datas:result.datas}
      }
    })
		
  }

	/*导出*/
	exportExcel = (dataKey) => {
    // WeaTools.downloadFile('/api/ec/dev/table/export','post',{dataKey:dataKey,filetype:'',filename:`${this.dialogStatus.meetingname}_${getLabel('509336','签到人员名单')}`})
		// // this.comsWeaTableStore[dataKey].exportAll();
    this.MeetingMemberExportExcelUrl  = encodeURI('/api/meeting/sign/exportMeetingSignExcel?'+`meetingId=${dataKey}`+'&_t='+new Date().getTime())
    if (!window.location.origin) {
      window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
		window.location.href = `${location.origin}${this.MeetingMemberExportExcelUrl}`
	}
	// 导出参会回执中参会人员
	exportMeetMemberExcel = ( params) => {
    this.MeetingMemberExportExcelUrl  = encodeURI('/api/meeting/base/exportExcel?'+this.buildUrlStr(params)+'&_t='+new Date().getTime())
    if (!window.location.origin) {
      window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
		window.location.href = `${location.origin}${this.MeetingMemberExportExcelUrl}`
	}

	buildUrlStr = (params = {}) => {
    let str = "";
    _.forIn(params, (value, key) => {
        str += `&${key}=${value}`;
    });
    if (str !== "")
        str = str.substring(1);
    return str;
  }

	//添加会议签到记录-弹出框
	changeTabSignTab = value => {
		this.dialogStatus = {
			...this.dialogStatus,
			tabSignTab: value
		}
	}

	//切换查看会议里的tab
	changePreviewMeetingTab = value => {
		this.dialogStatus = {
			...this.dialogStatus,
			previewmeetingTab: value,
		};
		if (value == '2') {
			this.topicViewActive = true;
		}
		if (value == '3') {
			this.serviceViewActive = true;
		}
	}

	//删除签到记录
	delSign = (value = {}, callback) => {
		API_LIST.delSign(value).then(data => {
			//判断下data
			data.api_status == true && API_LIST.getSignList({ meetingid: value.meetingid }).then((e) => {
				/* 暂时注释 等下修改 edit on 2017-12-22 */

				this.comsWeaTableStore = { ...this.comsWeaTableStore, [e.sessionkey]: new TableStore() };
				this.comsWeaTableStore[e.sessionkey].getDatas(e.sessionkey, 1);
				// this.comsWeaTableStore.getDatas(e.sessionkey, 1);
				this.dialogStatus = { ...this.dialogStatus, tabSignTable: e.sessionkey }
			});
			data.api_status == true && typeof callback === 'function' && callback();
		});
	}
	//补录
	signMeetingByHandOne = (value = {}, callback) => {
		API_LIST.signMeetingByHandOne(value).then(data => {
			//判断下data
			if(data.api_status == true){
				API_LIST.getSignList({ meetingid: value.meetingid }).then((e) => {
					/* 暂时注释 等下修改 edit on 2017-12-22 */
					// this.comsWeaTableStore.getDatas(e.sessionkey, 1);
					this.comsWeaTableStore = { ...this.comsWeaTableStore, [e.sessionkey]: new TableStore() };
					this.comsWeaTableStore[e.sessionkey].getDatas(e.sessionkey, 1);
					this.dialogStatus = { ...this.dialogStatus, tabSignTable: e.sessionkey }
				});
	
				data.api_status == true && typeof callback === 'function' && callback();
			}else{
				message.error(`${getLabel(384137,'操作失败！')}`);
			}
		});
	}

	//回执详细
	getReceiptTable = (value = {}) => {
		API_LIST.getReceiptTable(value).then(result => {
			//判断下data
			if(result.status === true){
				this.memberReceiptStore = { ...this.memberReceiptStore,
					backdate:result.backdate,
					backtime:result.backtime,
					begindate:result.begindate,
					begintime:result.begintime,
					bookroom:result.bookroom,
					bookticket:result.bookticket,
					isattend:result.isattend,
					memberid:result.memberid,
					recRemark:result.recRemark,
					recorderid:result.recorderid,
					roomstander:result.roomstander,
					ticketstander:result.ticketstander,
					othermember: result.othermember
				};
			}
		});
	}

	//回执详细
	getMemberListPageTree = (value = {}) => {
		API_LIST.getMemberListPageTree(value).then(e => {
			//判断下data
			const sessionkey = e.sessionkey;
			if(value.type == 1){
				this.hrmTabel.getDatas(sessionkey,1, '', '');
			}else{
				this.crmTabel.getDatas(sessionkey,1, '', '');
      }
      let tabMember = {...this.dialogStatus.tabMember,hrmnum:e.memberCount.data.attend+e.memberCount.data.otherCount,crmnum:e.memberCount.data.crmAttend,
        allAttend:e.memberCount.data.allAttend,allCrmAttend:e.memberCount.data.allCrmAttend}
      this.setDialogState({tabMember:tabMember})
			
		});
	}

	setLoading = (value) => {
		this.dialogStatus = {
			...this.dialogStatus,
			loading: value
		}
	}

	getTabSignTable = (value) => { 
		this.setLoading(true)
		this.comsWeaTableStore = { ...this.comsWeaTableStore, [value.sessionkey]: new TableStore() };
		this.comsWeaTableStore[value.sessionkey].getDatas(value.sessionkey, 1);
		this.dialogStatus = { ...this.dialogStatus, tabSignTable: value.sessionkey, loading: false }
		// API_LIST.getSignList({ meetingid: value.meetingid }).then((e) => {
		// 	this.comsWeaTableStore = { ...this.comsWeaTableStore, [e.sessionkey]: new TableStore() };
		// 	this.comsWeaTableStore[e.sessionkey].getDatas(e.sessionkey, 1);
		// 	this.dialogStatus = { ...this.dialogStatus, tabSignTable: e.sessionkey }
		// });
	}

	getTabSignDetailTable = (value) => { 
		this.setLoading(true)
		this.comsSignDetailWeaTableStore = { ...this.comsSignDetailWeaTableStore, [value.sessionkey]: new TableStore() };
		this.comsSignDetailWeaTableStore[value.sessionkey].getDatas(value.sessionkey, 1);
		this.dialogStatus = { ...this.dialogStatus, tabSignDetailTable: value.sessionkey, loading: false }
	}

	//查看会议-Decision-table
	getTabDecisionTable = (value = "") => {
		this.setLoading(true)
		this.comsWeaTableStore = { ...this.comsWeaTableStore, [value]: new TableStore() };
		this.comsWeaTableStore[value].getDatas(value, 1);
		this.dialogStatus = { ...this.dialogStatus, tabDecisionTable: value, loading: false }
	}

	getsignList = (params) =>{
		API_LIST.getSignList(params).then((e) => {
			this.comsWeaTableStore = { ...this.comsWeaTableStore, [e.sessionkey]: new TableStore() };
			this.comsWeaTableStore[e.sessionkey].getDatas(e.sessionkey, 1);
			this.dialogStatus = { ...this.dialogStatus, tabSignTable: e.sessionkey,tabSign:e }
		});
	}
	//查看会议-会议签到-添加会议签到记录
	signMeetingByHand = (value = {}, callback) => {
		API_LIST.signMeetingByHand(value).then(data => {
			if (data.api_status == true) {
				this.dialogStatus = {
					...this.dialogStatus,
					tabSignTab: false
				}
				API_LIST.getSignList({ meetingid: value.meetingid }).then((e) => {
					this.comsWeaTableStore = { ...this.comsWeaTableStore, [e.sessionkey]: new TableStore() };
					this.comsWeaTableStore[e.sessionkey].getDatas(e.sessionkey, 1);
					this.dialogStatus = { ...this.dialogStatus, tabSignTable: e.sessionkey }
				});
				typeof callback === 'function' && callback();
			}else{
				message.error(`${getLabel(384137,'操作失败！')}`);
			}
		});
	}

	delTopicDoc = (params, dataIndex) => {
		API_LIST.deltopicdoc(params).then((result) => {
      if(result.status){
        let tabTopic = { ...this.dialogStatus.tabTopic };
        let data = { ...tabTopic.datas[dataIndex] };
        let doclist = [];
        data.doclist.forEach((d) => {
          if (d.id != params.id) {
            doclist.push({ ...d });
          }
        });
        data.doclist = doclist;
        tabTopic.datas[dataIndex] = data;
        this.dialogStatus = { ...this.dialogStatus, tabTopic: tabTopic }
      }else {
        message.error(`${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	addTopicDoc = (params, dataRecord) => {
		API_LIST.addtopicdoc(params).then((result) => {
			if(result.status){
        let tabTopic = { ...this.dialogStatus.tabTopic };
        let dataIndex = -1;
        tabTopic.datas.forEach((record, index) => {
          if (dataRecord.id == record.id) {
            dataIndex = index;
          }
        });
        if (dataIndex < 0) return;
        tabTopic.datas[dataIndex].doclist.push(result);
        this.dialogStatus = { ...this.dialogStatus, tabTopic: tabTopic }
			}else {
        message.error(`${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	setTopicNewTime = (meetingId, topicId, reshowArray) => {
		let tabTopic = { ...this.dialogStatus.tabTopic };
		let dataIndex=-1;
		tabTopic.datas.forEach((record, index) => {
			if (topicId == record.id) {
				dataIndex = index;
			}
		});
		if (dataIndex==-1) return;
		tabTopic.datas[dataIndex].topicdate = reshowArray;
		this.dialogStatus = { ...this.dialogStatus, tabTopic: tabTopic }
	}

	setNewRemark = (remark) => {
		let tabMember = { ...this.dialogStatus.tabMember };
		tabMember.othersremark = remark;
		this.dialogStatus = { ...this.dialogStatus, tabMember: tabMember }

	}

	/**
 * 设置新回执
 */
	setNewReply = (showValue, formValue, type) => {
		let tabMember = { ...this.dialogStatus.tabMember };
		let hrmTabel = { ...this.hrmTabel };
		let datas = type == 'hrm' ? hrmTabel.datas : tabMember.crmdatas;
		let idx = datas.findIndex((ele) => ele.recorderid == formValue.recorderid);
		let isattend = type == 'hrm' ? datas[idx].isattend : datas[idx].values.isattend;
		if (isattend != formValue.isattend) {
			if (formValue.isattend == '1') {
				if(type == 'hrm'){
					tabMember.hrmnum = 0 ;
					hrmTabel.datas.forEach((element, index) => {
						if (element.isattend === '1' ){
							tabMember.hrmnum ++;
						}
					})
					tabMember.hrmnum ++;
				} else{
					tabMember.crmnum = 0 ;
					tabMember.crmdatas.forEach((element, index) => {
						if (element.isattend === '1' ){
							tabMember.crmnum ++;
						}
					})
					tabMember.crmnum++;
				}
			} else if (isattend == '1') {
				type == 'hrm' ? tabMember.hrmnum-- : tabMember.crmnum--;
			}
		}
		let data = { ...datas[idx], ...showValue, values: formValue };
		data.memberid = formValue.memberid;
		data.recorderid = formValue.recorderid;
		datas[idx] = data;
		this.hrmTabel = { ...this.hrmTabel, hrmTabel: hrmTabel }
		this.dialogStatus = { ...this.dialogStatus, tabMember: tabMember }

	}

	//删除
	exchangeDelete = (value) => {
		API_LIST.exchangeDelete(value).then(data => {
			if(data.status){
        this.getExchangeList({ meetingid: value.meetingid })
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})
	}

	//获取相关交流信息
	getExchangeList = (value) => {
		API_LIST.getExchangeList(value).then(data => {
			let exchange = { ...data }
			exchange.datas.forEach((element, index) => {
				element.isEdit = false
			})
			exchange.datas.unshift({
				id: 'create',
				isEdit: true,
				remark: '',
				docids: [],
				projectids: [],
				relatedcus: [],
				relateddoc: [],
				relatedprj: [],
				relatedwf: [],
			})

			this.dialogStatus = { ...this.dialogStatus, exchangeList: exchange }
		})
	}

	//相关交流datas循环
	changeDiscussList = (value = {}) => {
		this.dialogStatus = { ...this.dialogStatus, exchangeList: value }
	}

	//相关交流提交
	exchangeSave = (value) => {
		API_LIST.exchangeSave(value).then(data => {
      if(data.status){
        this.getExchangeList({ meetingid: value.meetingid });
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})
	}

	//会议决议modal显隐
	getDecisionDataNew = (value, callback) => {
		value && API_LIST.getDecisionData({ meetingid: value }).then(data => {//打开
			// this.dialogStatus = { ...this.dialogStatus, decisionStatus: data }
			this.decisionStatus = data;
			if (callback) callback();
		})
		if (!value) {
			this.decisionStatus = {}
			// this.dialogStatus = { ...this.dialogStatus, decisionStatus: '' }
			if (callback) callback();
		}
	}

	//提交决议modal
	decisionSubmit = (value, callback) => {
		this.dialogStatus.submitLoading=true;
		API_LIST.decisionSubmit(value).then(data => {
			this.dialogStatus.submitLoading=false;
			if (data.status) {
				if (callback) callback();
			}else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`)
      }
		});
	}

	//保存决议modal
	decisionSave = (value, callback) => {
		this.dialogStatus.saveLoading=true;
		API_LIST.decisionSave(value).then(data => {
			this.dialogStatus.saveLoading=false;
			if (data.status) {
				if (callback) callback();
			}else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	//提前结束modal受控
	advanceModal = (value = {}, params = '') => {
		if (params) {
			this.dialogStatus = { ...this.dialogStatus, advanceModalparams: params, advanceModal: value }
		} else {
			this.dialogStatus = { ...this.dialogStatus, advanceModal: value }
		}
	}

	StopIntvl = (value, callback) => {
		this.dialogStatus.endRepeatLoading = true;
		API_LIST.StopIntvl(value).then(data => {
            this.dialogStatus.endRepeatLoading = false;
      if(data.status){
        if (callback) callback(value.meetingid);
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})
	}

	//取消周期会议
	cancelIntvl = (value = {}, callback) => {
		API_LIST.cancelIntvl(value).then(data => {
      if(data.status){
        this.doInit('', false);
        if (callback) callback();
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	//停止重复会议
	onStopIntvl = (value = {}, callback) => {
		API_LIST.onStopIntvl(value).then(data => {
      if(data.status){
        this.doInit('', false);
        if (callback) callback();
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		});
	}
	//结束会议
	overMeeting = (value = {}, callback) => {
		API_LIST.overMeeting(value).then(data => {
      if(data.status){
        if (callback) callback();
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	//复制会议
	copy = (value = {}, callback) => {
		//设置复制按钮的disabled和onlaoding,因为前段虽然有了这个但是还有一个时间差才会不显示复制按钮
		//所以在getpreview中才将repeatLoading设置为false
		let repeatBtnChk = this.dialogStatus.repeatLoading;
		if(repeatBtnChk == true){
			return;
		}else{
			this.dialogStatus.repeatLoading=true;
		}
		API_LIST.copy(value).then(data => {
      if(data.status){
        if (callback) callback(data.meetingid);
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		});
	}

	//取消会议
	cancelMeeting = (value = {}, callback) => {
		API_LIST.cancelMeeting(value).then(data => {
      if(data.status){
        this.doInit('', false)
        if (callback) callback();
      }else {
        message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
        if (callback) callback();
      }
		});

	}

	//批准
	doSubmit = (value,callback,errorCallback) => {
		API_LIST.doSubmit(value).then(data => {
      if(data.status){
        if (callback) callback();
      }else {
				if(errorCallback) errorCallback();
        //message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})

	}

	//提交审批
	doSubmit2 = (value, callback,errorCallback) => {
		API_LIST.doSubmit2(value).then(data => {
      if(data.status){
        if (callback) callback();
      }else {
				if(errorCallback) errorCallback();
        //message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})

	}
	//退回
	doReject = (value, callback,errorCallback) => {
		API_LIST.doReject(value).then(data => {
      if(data.status){
        if (callback) callback();
      }else {
				if(errorCallback) errorCallback();
        //message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})

	}

	//提交审批
	reSubmit = (value, callback,errorCallback) => {
		API_LIST.reSubmit(value).then(data => {
			this.dialogStatus.submitLoading=false;
      if(data.status === true){
        if (callback) callback();
      }else {
				if(errorCallback) errorCallback();
        //message.error(data.error ? data.error : `${getLabel(384137,'操作失败！')}`);
      }
		})
	}

	//删除
	doDelete = (value = {}, callback) => {
		API_LIST.doDelete(value).then(data => {
      if(data.api_status){
        if (callback) callback();
      }else {
        message.error(result.error ? result.error : getLabel(384137,'操作失败！'));
      }
		});
	}

	//二维码下载
	downLoadQrCode = (params)=>{
		API_LIST.downLoadQrCode(params);
	}

  //二维码刷新
  getQrCode = (params, callback) => {
    params = { ...params,
      ismobile: 1
    };
    return API_LIST.getQrCode(params)
  }

	// 根据选择服务项目取得对应的负责人
	getServeProHrmIds = (params)=>{
    API_LIST.getServeProHrmIds(params).then(result => {
    });
  }

  // 记录页面渲染时间
	saveSystemPageViewLog = (params)=>{
    params={
      ...params,
      url:window.location.href,
      clientType: this.getBrowserVersion(),
      interfaceTc: (this.interfaceTc_after || 0) - (this.interfaceTc_start || 0),
      serviceTc: this.server_duration,
      // renderTc: (this.renderTc_after || 0) - (this.renderTc_start || 0),
      staticTc: '',
      allTc:  (this.allTc_after || 0) - (this.allTc_start || 0),
    }
    API_LIST.saveSystemPageViewLog(params).then(result => {
    });
  }

  //获取浏览器版本
  getBrowserVersion = () => {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
    if (isChrome)
        return "Chrome";

    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isEdge)
        return "Edge";
    if(isIE11)
        return "IE11";
    if (isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion == 7)
            return "IE7";
        else if (fIEVersion == 8)
            return "IE8";
        else if (fIEVersion == 9)
            return "IE9";
        else if (fIEVersion == 10)
            return "IE10";
        else if (fIEVersion == 11)
            return "IE11";
        else
            return "IE";
    }
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
    var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
    var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器  
    if (isOpera)
        return "Opera";
    if (isFF)
        return "FF";
    if (isSafari)
        return "Safari";
    return "unident";
  }

  //获得接口耗时
  getApi_duration_start=()=>{
    this.interfaceTc_start = new Date().getTime()
  }

  getApi_duration_after=()=>{
    this.interfaceTc_after = new Date().getTime()
  }

  //获得渲染耗时
  setRender_start=()=>{
    this.renderTc_start = new Date().getTime()
  }

  setRender_after=()=>{
    this.renderTc_after = new Date().getTime()
  }

  //获得总耗时
  setAll_start=()=>{
    this.allTc_start = new Date().getTime()
  }

  //获得总耗时
  setAll_after=()=>{
    this.allTc_after = new Date().getTime()
  }

  setServer_duration = (serverCost)=>{
    this.server_duration = serverCost
	}
	
	// 会议签到,签退 start

	setSignStatus = (params={}) => {
		Object.keys(params).forEach(key => {
			this.signStatus = {
				...this.signStatus,
				[key]: params[key]
			};
		});
		if (params.limitDialogVisible) { // 当更改签退时间弹框显示
			this.getDefaultSignBackTime();
		}
	}

	//获取会议签到，签退统计人数
	getSignInfoCount = (params) => {
		this.signDataStatistic = {
			allMember: 0,
			signCount: 0,
			notSignCount: 0,
			signBackCount: 0,
			notSignBackCount: 0,
			ztrs: 0, 
			cdrs: 0,
			allowSignBack:false
		};
		API_LIST.getSignInfoCount(params).then(res => {
			if (res && res.api_status && res.data) {
				this.signDataStatistic = {
					...this.signDataStatistic,
					allMember: res.data.allMember,
					signCount: res.data.signCount,
					notSignCount: res.data.notSignCount,
					signBackCount: res.data.signBackCount,
					notSignBackCount: res.data.notSignBackCount,
					ztrs: res.data.ztrs, 
					cdrs: res.data.cdrs,
					allowSignBack: res.data.allowSignBack,
				};
			}
		});
	}

	// 获取会议签到，签退列表详情
	getSignInfo = (params, callback) => {
		// this.comsWeaTableStore = {};
		API_LIST.getSignInfo(params).then(res => {
			typeof callback === 'function' && callback(res);
		});
	}

	// 获取会议签到，签退高级搜索
	getSignInfoSearchCondition = (params) => {
		API_LIST.getSignInfoSearchCondition(params).then(res => {
			if (res && res.api_status) {
				this.signStatus.form.initFormFields(toJS(res.condition));
				this.signStatus.conditionInfo =  res.condition;
			}
		});
	}

	// 更改签退时间-form
	getDefaultSignBackTime = (param) => {
		const {meetingId} = this.dialogStatus
		let params = {...param,meetingid:meetingId}
		API_LIST.getDefaultSignBackTime(params).then(res => {
			if (res && res.api_status) {
				this.signStatus.limitForm.initFormFields(toJS(res.fields));
				this.signStatus.limitConditionInfo =  res.fields;
			}
		});
	}

	// 保存更改签退时间设置
	saveDefaultSignBackTime = (param, callback) => {
		const {meetingId} = this.dialogStatus
		let params = {...param,meetingid:meetingId}
		API_LIST.saveDefaultSignBackTime(params).then(res => {
			if (res && res.api_status) {
				typeof callback === 'function' && callback(); 
			}
		});
	}

	// 补录签退时间
	signBackMeetingByHandOne = (params, callback) => {
		API_LIST.signBackMeetingByHandOne(params).then(res => {
			if (res.api_status) {
				typeof callback === 'function' && callback();
			}
		});
	}

	onSearch = (params) => {
		API_LIST.onSearch(params).then(res => {

		});
	}

	// 会议签到,签退 end

	//会议回执改造===============start
	@observable 
	receiptFormStatus = {
		form: new WeaForm(),
		form2: new WeaForm(),
		receiptFormCondition: [],
		isCrmReceiptDetail:false,
		crmCol:[],
		crmCondition:[],
		datas:[],
		formValue:{},
		visible:false,
		token:'',
	}

	@action
  clearForm( form ) {
    return form.resetForm();
	}

	@action
  getReceiptFormParams( form ) {
    return form.getFormParams();
	}

	@action
	setReceiptFormStatus = (params={}) => {
		Object.keys(params).forEach(key => {
			this.receiptFormStatus = {
				...this.receiptFormStatus,
				[key]: params[key]
			};
		});
	}

	
	//会议回执改造===============end


	//会议签到QC727172==============start
	@observable
	signInfoStatus = {
		SignInfoConditions: [],
		token: '',
		signInfoVisible: false,
		signInfo:{},
		position:[],
		mapVisible:false,
	}


	@action
	setSignInfoStatus=(params={})=>{
		Object.keys(params).forEach(key => {
			this.signInfoStatus = {
				...this.signInfoStatus,
				[key]: params[key]
			};
		});
	}

	@action
	openSignInfo=(params)=>{
		API_LIST.getSignInfoSite(params).then(res=>{
			this.signInfoStatus.signInfo=res
			this.signInfoStatus.signInfoVisible=true
		})
	}
	//会议签到QC727172==============end
}